import axios from 'axios'
import { Message } from 'element-ui'
import router from '@/router/index'
import { getToken } from '@/utils/auth'

// const proxy = {
//   baseURL: process.env.VUE_APP_BASE_API
// }
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  // baseURL: '/api/10559/door/doorDataJson.json',
  timeout: 50000,
  withCredentials: true
})
service.interceptors.request.use(
  config => {
    config.headers.Authorization = getToken()
    // config.headers['Content-Type'] = 'multipart/form-data'
    // config.headers.Authorization = window.localStorage.getItem('token')
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    const { data, status } = response
    if (status !== 200) {
      Message({
        message: data.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
    } else {
      const code = data.code
      const message = data.message
      if (code === -1) {
        Message({
          message: '网络异常，系统繁忙！',
          type: 'error',
          duration: 5 * 1000
        })
      } else if (code > 0) {
        Message({
          message: message,
          type: 'error',
          duration: 5 * 1000
        })
      }
      // if (code === -1) {
      //   Message({
      //     message: '网络异常，请稍后重试',
      //     type: 'error',
      //     duration: 5 * 1000
      //   })
      // } else if (code === 6002) {
      //   Message({
      //     message: '验证码错误',
      //     type: 'error',
      //     duration: 5 * 1000
      //   })
      // } else if (code === 6003) {
      //   Message({
      //     message: '用户名/密码错误',
      //     type: 'error',
      //     duration: 5 * 1000
      //   })
      // } else if (code === 401) {
      //   Message({
      //     message: '登录超时，请重新登录',
      //     type: 'error',
      //     duration: 5 * 1000
      //   })
      // } else if (code === 422) {
      //   Message({
      //     message: '参数错误',
      //     type: 'error',
      //     duration: 5 * 1000
      //   })
      // }
      return data
    }
  },
  error => {
    console.log(error)
    const response = error.response
    const { status } = response
    if (status === 401) {
      Message({
        message: '登录失效，请重新登录',
        type: 'error',
        duration: 5 * 1000
      })
      router.push({ name: 'Login' })
    }
    if (status === 403) {
      Message({
        message: '角色没有权限！',
        type: 'error',
        duration: 5 * 1000
      })
    }
  }
)

export default service
